#! /usr/bin/python -S

########################################################
# Part of MILIM NIRDAFOT project.
# Written by H. Magal, 2014
# See details on the project at the site:
#   https://sites.google.com/site/nirdafotdownloads/home
########################################################

import sys
if __name__ == '__main__':
    sys.setdefaultencoding("utf-8")         # this is needed for the windows.
    import site                             # we call python with -S, so now we import the site module

import os
import platform
import wx
import md5
import codecs
import hebrew_fixed_texts
import constants


# returns file name as string
def generate_file_name ():
    md = md5.new()
    md.update (platform.node())             # add node name to MD5
    md.update (':')
    md.update (constants.path_4_data_files)  # add CWD() to MD5
    return constants.path_4_data_files + 'lic.' + md.hexdigest () + '.txt'


# display simple dialog box and exit program on a fatal error
def fatal_error_and_exit (msg1, msg2):
    msg3 = msg2 + '\nProgram is going to quit ...'
    wx.MessageBox (msg3, msg1, wx.OK | wx.ICON_ERROR)
    sys.exit (1)


# main license frame class
class MyLicFrame (wx.Frame):
    """ make a frame, inherits wx.Frame """
    def __init__ (self):
        if constants.platform_is_Win is True:               # we change it only for current frame
            local = wx.Locale (wx.LANGUAGE_HEBREW)          # set right to Left Locale. It is a MUST for windows
        ds = wx.DisplaySize()   # get screen dimensions
        height = ds [1]
        width = ds [0]
        frame_width = (width*9) / 10
        frame_height = (height*9) / 10
        # create a frame, no parent, default to wxID_ANY. The frame cannot be resized/maximized
        # the frame is generated to be positioned at the screen regarding the screen properties
        wx.Frame.__init__ (self, None, wx.ID_ANY, 'Accept Program License', pos=(width/20, height/20), size=(frame_width, frame_height),
                           style=(wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN))

        panel = wx.Panel (self)

        sizer = wx.BoxSizer (wx.VERTICAL)

        GPLv3file = codecs.open (constants.path_4_data_files + 'GPLv3.Hebrew.UTF8.txt', 'r', 'utf-8')
        lines = GPLv3file.readlines ()                          # read all lines into a list of lines
        GPLv3file.close ()
        jline = ''.join (lines)                                 # join all lines into one string
        text = wx.TextCtrl (panel, style=wx.SIMPLE_BORDER | wx.VSCROLL | wx.TE_READONLY | wx.TE_MULTILINE | wx.TE_WORDWRAP,
                            size=((frame_width*99)/100, (frame_height*6)/7))
        text.AppendText (jline)
        text.SetInsertionPoint (0)
        text.Refresh ()
        sizer.Add (text, flag=wx.ALL | wx.EXPAND, border=4)

        t_pnl = wx.Panel (panel)                                # Create intermediate sub panel
        t_pnl.SetBackgroundColour (wx.GREEN)
        if constants.platform_is_Win is True:
            wx.StaticText (t_pnl,  label=hebrew_fixed_texts.license_message)  # create static text and position it in the intermediate panel
        else:
            wx.StaticText (t_pnl, label=hebrew_fixed_texts.use_one_button)
        tsizer = wx.BoxSizer (wx.HORIZONTAL)
        tsizer.Add (t_pnl, proportion=1)                        # add intermediate panels to sizer

        t_pnl = wx.Panel (panel)                                # Create intermediate sub panel
        t_pnl.SetBackgroundColour (wx.GREEN)
        wx.StaticText (t_pnl,  label=hebrew_fixed_texts.scroll_license_text)
        tsizer.Add (t_pnl, proportion=1)                        # add intermediate panels to sizer

        t_pnl = wx.Panel (panel)                                # Create intermediate sub panel
        t_pnl.SetBackgroundColour (wx.GREEN)
        if constants.platform_is_Win is True:
            wx.StaticText (t_pnl, label=hebrew_fixed_texts.use_one_button)
        else:
            wx.StaticText (t_pnl,  label=hebrew_fixed_texts.license_message)  # create static text and position it in the intermediate panel
        tsizer.Add (t_pnl, proportion=1)                        # add intermediate panels to sizer
        sizer.Add (tsizer, flag=wx.ALL | wx.EXPAND, border=2)

        bsizer = wx.BoxSizer (wx.HORIZONTAL)
        buttonOk = wx.Button (panel, label=hebrew_fixed_texts.accept_license)
        buttonOk.SetForegroundColour (wx.GREEN)
        buttonOk.Bind (wx.EVT_BUTTON, self.OnAccept)
        buttonOk.Refresh ()
        buttonRefuse = wx.Button (panel, label=hebrew_fixed_texts.refuse_license)
        buttonRefuse.SetForegroundColour (wx.RED)
        buttonRefuse.Bind (wx.EVT_BUTTON, self.OnRefuse)
        self.Bind (wx.EVT_CLOSE,          self.OnRefuse)                    # I treat close as with Refuse button
        buttonRefuse.Refresh ()
        if constants.platform_is_Win is True:
            bsizer.Add (buttonOk, flag=wx.LEFT | wx.RIGHT, proportion=1, border=20)
            bsizer.Add (buttonRefuse, flag=wx.LEFT | wx.RIGHT, proportion=1, border=20)
        else:
            bsizer.Add (buttonRefuse, flag=wx.LEFT | wx.RIGHT, proportion=1, border=20)
            bsizer.Add (buttonOk, flag=wx.LEFT | wx.RIGHT, proportion=1, border=20)
        sizer.Add (bsizer, flag=wx.EXPAND)

        panel.SetSizer (sizer)
        panel.Layout ()
        self.Show (True)                                        # show the frame


    def OnRefuse (self, evt):
        fatal_error_and_exit ('Program license refusal', "You cann't use the program if you don't agree to terms of use.")


    def OnAccept (self, evt):
        try:
            f = open (generate_file_name (), 'w')
            f.write ('a')                       # keep it the same string as checked by check_existing_accept_file ()
            f.close ()
        except:
            fatal_error_and_exit ('File Error', 'File Creation/Writing failed')
        self.Destroy ()                         # destroy this frame an start the words game


# returns True if a legal file does exist, False otherwise
def check_existing_accept_file ():
        s = ''                                  # init to empty string
        try:
            f = open (generate_file_name (), 'r')
            s = f.read ()
            f.close ()
        except:
            return False

        return (s == 'a')                       # this is the file content for good file



######### Main #########
# this function is for the stand alone debug of the license mechanism
def main ():
    constants.set_platform_dependent_vars ()
    e = check_existing_accept_file ()
    if e is True:
        return
    app = wx.App ()
    lwindow = MyLicFrame ()         # call class MyLicFrame
    app.MainLoop ()                 # start the event loop


if __name__ == '__main__':
    main ()